//
//  NSDate+DateCompare.swift
//  CLExtension
//
//  Created by CharlieLiao on 2017/8/7.
//  Copyright © 2017年 Charlie. All rights reserved.
//

extension Date
{
    ///
    public var year: Int { NSDate.cl_Calendar.component(.year, from: self) }
    ///
    public var month: Int { NSDate.cl_Calendar.component(.month, from: self) }
    ///
    public var day: Int { NSDate.cl_Calendar.component(.day, from: self) }
    ///
    public var hour: Int { NSDate.cl_Calendar.component(.hour, from: self) }
    ///
    public var minute: Int { NSDate.cl_Calendar.component(.minute, from: self) }
    ///
    public var weekday: Int { NSDate.cl_Calendar.component(.weekday, from: self) }
    
    public var isToDay: Bool { NSDate.cl_Calendar.isDateInToday(self) }
    
    public var isTomorrow: Bool { NSDate.cl_Calendar.isDateInTomorrow(self) }
    
    public var isYesterday: Bool { NSDate.cl_Calendar.isDateInYesterday(self) }
    
    
    public init?(_ year: Int, _ month: Int, _ day: Int, _ hour: Int?=nil, _ minute: Int?=nil, _ second: Int?=nil) {
        
        let components = DateComponents(calendar: NSDate.cl_Calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second)
        
        if let date = components.date {
            self = date
        } else {
            return nil
        }
    }
    
    /// 两个时间是否为同一天
    public func isSameDay(_ date: Date) -> Bool
    {
        return NSDate.cl_Calendar.isDate(date, inSameDayAs: self)
    }
    
    /// 两个时间相差的天数
    public func betweenNumber(_ date: Date) -> Int?
    {
        let calendar = NSDate.cl_Calendar
        
        // 先把时分秒统一为0点
        let selfDate = calendar.startOfDay(for: self)
        let otherDate = calendar.startOfDay(for: date)
        
        // 再进行比较
        let set = Set<Calendar.Component>(arrayLiteral: .day)
        let comps = calendar.dateComponents(set, from: selfDate, to: otherDate)
        return comps.day
    }
    
    public func add(Days: Int) -> Date?
    {
        return NSDate.cl_Calendar.date(byAdding: .day, value: Days, to: self)
    }
    
    public func add(Months: Int) -> Date?
    {
        return NSDate.cl_Calendar.date(byAdding: .month, value: Months, to: self)
    }
    
    
    public func add(Years: Int) -> Date?
    {
        return NSDate.cl_Calendar.date(byAdding: .year, value: Years, to: self)
    }
    
}
